﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;
using CodeCarvings.Piczard.Web;
using CodeCarvings.Piczard;
using System.IO;
using System.Xml.Linq;
using CodeCarvings.Piczard.Filters.Watermarks;

namespace Framework.WebmasterTool
{
    public partial class Default : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CheckPermission();
                LoadInfomation();
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.Company.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        public void ImageUpload(SimpleImageUpload ctrImageUpload)
        {
            ctrImageUpload.ImageBackColorApplyMode = PictureTrimmerImageBackColorApplyMode.DoNotApply;
            ctrImageUpload.CropConstraint = new FreeCropConstraint();
            ctrImageUpload.PreviewFilter = new FixedResizeConstraint(200, 200, System.Drawing.Color.Black);
            ctrImageUpload.Text_BrowseButton = "Upload ảnh";
            ctrImageUpload.Text_CancelUploadButton = "Huỷ";
            ctrImageUpload.Text_EditButton = "Sửa ảnh";
            ctrImageUpload.Text_RemoveButton = "Xoá ảnh";
        }

        public void CleanImageUploadTemp()
        {
            foreach (var file in Directory.GetFiles(Server.MapPath(ConfigPaths.Path_ImageUploadTemp_Folder_MapPath)))
            {
                File.Delete(file);
            }
        }

        public XElement LoadInfomationCompany()
        {
            XDocument xDocInfo = XDocument.Load(Server.MapPath(ConfigPaths.Path_Infomation_Xml));
            XElement xECompany = xDocInfo.Descendants("company").FirstOrDefault();
            return xECompany;
        }

        public XElement LoadInfomationConfigWebsite()
        {
            XDocument xDocInfo = XDocument.Load(Server.MapPath(ConfigPaths.Path_Infomation_Xml));
            XElement xECompany = xDocInfo.Descendants("ConfigWebsite").FirstOrDefault();
            return xECompany;
        }

        public void LoadInfomation()
        {
            XElement xEInfomationCompany = LoadInfomationCompany();            
            txtCompanyName.Text = xEInfomationCompany.Element("companyname").Value.Trim();
            txtCompanyName_en.Text = xEInfomationCompany.Element("companyname_en").Value.Trim();
            txtAddress.Text = xEInfomationCompany.Element("address").Value.Trim();
            txtAddress_en.Text = xEInfomationCompany.Element("address_en").Value.Trim();
            txtEmail.Text = xEInfomationCompany.Element("email").Value.Trim();
            txtPhone.Text = xEInfomationCompany.Element("phone").Value.Trim();
            txtFax.Text = xEInfomationCompany.Element("fax").Value.Trim();
            txtWebsite.Text = xEInfomationCompany.Element("website").Value.Trim();
            txtSlogan.Text = xEInfomationCompany.Element("text_slogan").Value.Trim();
            txtSlogan_en.Text = xEInfomationCompany.Element("text_slogan_en").Value.Trim();
            txtFacebook.Text = xEInfomationCompany.Element("facebook").Value.Trim();
            XElement xEInfomationConfigWebsite = LoadInfomationConfigWebsite();
            XElement xEUnderContructionEnable = xEInfomationConfigWebsite.Descendants("UnderContruction").FirstOrDefault().Descendants("Enable").FirstOrDefault();
            XElement xEUnderContructionTimePublish = xEInfomationConfigWebsite.Descendants("UnderContruction").FirstOrDefault().Descendants("TimePublish").FirstOrDefault();
            if (xEUnderContructionEnable.Value.Trim() == "0")
            {
                chkUnderContruction.Checked = false;
            }
            else
            {
                chkUnderContruction.Checked = true;
            }
            txtRealeaseDate.Text = String.Format("{0:dd/MM/yyyy}", xEUnderContructionTimePublish.Value.Trim());

            txtTitlePage.Text = xEInfomationConfigWebsite.Element("Title").Value.Trim();
        }

        private void SaveInfomation()
        {
            XDocument xDocInfomation = XDocument.Load(Server.MapPath(ConfigPaths.Path_Infomation_Xml));
            XElement xEInfomationCompany = xDocInfomation.Descendants("company").FirstOrDefault();
            xEInfomationCompany.Element("companyname").Value = txtCompanyName.Text.Trim();
            xEInfomationCompany.Element("companyname_en").Value = txtCompanyName_en.Text.Trim();
            xEInfomationCompany.Element("address").Value = txtAddress.Text.Trim();
            xEInfomationCompany.Element("address_en").Value = txtAddress_en.Text.Trim();
            xEInfomationCompany.Element("email").Value = txtEmail.Text.Trim();
            xEInfomationCompany.Element("phone").Value = txtPhone.Text.Trim();
            xEInfomationCompany.Element("fax").Value = txtFax.Text.Trim();
            xEInfomationCompany.Element("website").Value = txtWebsite.Text.Trim();
            xEInfomationCompany.Element("text_slogan").ReplaceNodes(new XCData(txtSlogan.Text));
            xEInfomationCompany.Element("text_slogan_en").ReplaceNodes(new XCData(txtSlogan_en.Text));
            xEInfomationCompany.Element("facebook").Value = txtFacebook.Text.Trim();
            XElement xELogo = xEInfomationCompany.Element("image_logo");
            XElement xEBanner = xEInfomationCompany.Element("image_banner");
           
            XElement xEInfomationConfigWebsite = xDocInfomation.Descendants("ConfigWebsite").FirstOrDefault();
            XElement xEUnderContructionEnable = xEInfomationConfigWebsite.Descendants("UnderContruction").FirstOrDefault().Descendants("Enable").FirstOrDefault();
            XElement xEUnderContructionTimePublish = xEInfomationConfigWebsite.Descendants("UnderContruction").FirstOrDefault().Descendants("TimePublish").FirstOrDefault();
            if (chkUnderContruction.Checked == true)
            {
                xEUnderContructionEnable.Value = "1";
            }
            else
            {
                xEUnderContructionEnable.Value = "0";
            }
            xEUnderContructionTimePublish.Value = !string.IsNullOrEmpty(txtRealeaseDate.Text.Trim()) ? DateTime.ParseExact(txtRealeaseDate.Text.Trim(), "dd/MM/yyyy", null).ToShortDateString() : "";
            xEInfomationConfigWebsite.Element("Title").Value = txtTitlePage.Text.Trim();
            xDocInfomation.Save(Server.MapPath(ConfigPaths.Path_Infomation_Xml));
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            SaveInfomation();
            //CleanImageUploadTemp();
            LoadInfomation();
            lblMassage.Visible = true;

            //create log in database
            CreateDBLog(null, null, TypeAction.Update, "Cập nhật cấu hình chung", "", "", "", "", "", "", "", "");

            //clear outputcache
            HttpResponse.RemoveOutputCacheItem("/Default.aspx");
            HttpResponse.RemoveOutputCacheItem("/Articles.aspx");
            HttpResponse.RemoveOutputCacheItem("/ArticleDetails.aspx");
            HttpResponse.RemoveOutputCacheItem("/Products.aspx");
            HttpResponse.RemoveOutputCacheItem("/ProductDetails.aspx");
            HttpResponse.RemoveOutputCacheItem("/Contact.aspx");
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            //CleanImageUploadTemp();
            LoadInfomation();
            lblMassage.Visible = false;
        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
        string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}